<?php
$loader->requireOnce('includes/EwhImport/EwhImportDrugMaterialProc.class.php');

/**
 * Controler for import drug/material.
 * @package modules.dept_pharmacy.controllers
 * @author viethd
 * @version $Id$
 * @copyright 2009 LHV Company
 */
class C_EwhImportDrugMaterial extends Controller {
    private $logger ;
    private $phaImportPro;
    function __construct($template_mod = "general") {
        parent::Controller();
        $this->setLayout('pha_ewh');
        $this->logger = LoggerManager::getLogger('module.dept_pharmacy.controllers.C_EwhImportDrugMaterial');
        $this->template_mod = $template_mod;
        $this->view->path="pha_ewh_import_drug_material";
        $this->phaImportPro = new EwhImportDrugMaterialProc($this);
    }

    public function actionDisplayImportPage() {
        $this->logger->info('Start actionDisplayImportPage');
        $this->assignDefaultValueforCreatingImTicket();
        $this->assign('isEdit', false);
        $html = $this->view->render('import_page.html');
        $this->logger->info('Finish actionDisplayImportPage');
        return $html;
    }

    public function actionDisplayEditImTickPage() {
        $this->logger->info('Start actionDisplayEditImTickPage');
        $this->assignDefaultValueforCreatingImTicket();
        $this->assign('isEdit', true);
        $html = $this->view->render('import_page.html');
        $this->logger->info('Finish actionDisplayEditImTickPage');
        return $html;
    }

    public function actionDoSearchImTicketAjax() {
        $this->logger->info('Start actionEditImTicketAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        $fDate = '';
        $tDate = '';
        if ($_POST['fromDateyyyy'] != '' && $_POST['fromDatemm'] && $_POST['fromDatedd']) {
            $fDate = sprintf("%04s-%02s-%02s 00:00:00", $_POST['fromDateyyyy']
            , $_POST['fromDatemm'], $_POST['fromDatedd']);
        }
        if ($_POST['toDateyyyy'] != '' && $_POST['toDatemm'] && $_POST['toDatedd']) {
             
            $tDate = sprintf("%04s-%02s-%02s 23:59:59", $_POST['toDateyyyy']
            , $_POST['toDatemm'], $_POST['toDatedd']);
        }

        //only get out the imticket not valuated yet
        $filter = array(
            "imTicketCode"  =>  $_POST['imTicketCode'],
            "fromDate"      =>  $fDate,
            "toDate"        =>  $tDate,
            "valuated"      => 0,
            "finalized"     => 0
        );

        $arrImTicket = $this->phaImportPro->searchImticket($filter);
        $this->assign('arrImTicket', $arrImTicket);
        $result['result'] = $this->view->render('edit_import_search_result.html');
        $this->logger->info('Finish actionEditImTicketAjax');
        return json_encode($result);
    }

    public function actionDeleteImTicketAjax() {
        $this->logger->info('Start actionEditImTicketAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        $imTicketId = $_POST['imTicketId'];
        $result['result'] = $this->phaImportPro->deleteImticket($imTicketId);
        $this->assign('arrImTicket', $arrImTicket);
        $this->logger->info('Finish actionEditImTicketAjax');
        return json_encode($result);
    }

    public function actionEditImTicketAjax() {
        $this->logger->info('Start actionEditImTicketAjax');

        $imTicketId = '';
        if (isset($_POST['imTicketId'])) {
            $imTicketId = $_POST['imTicketId'];
        }

        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        try
        {
            $this->assignDefaultValueforEditingImTicket();
            if ($imTicketId != '') {

                $imTicketObj = $this->phaImportPro->getImTicketObj($imTicketId);
                $arrItemsOfImTicket = $this->phaImportPro->getArrItemsOfImTicket($imTicketId);

                $datePart =  L10nHelper::getDateParts(
                L10nHelper::renderDateTime($imTicketObj->get('date'),'short', 'datetime')
                );        
                $personObj = Celini::newOrdo('Person');
                $personObj->setup($imTicketObj->get('input_user_id'));
                        
                $loginUser = array(
                    'userId'=>$imTicketObj->get('input_user_id'),
                    'userName'=> $personObj->get('name')
                );
                $this->assign('imticketCode', $imTicketObj->get('imticket_code'));
                $this->assign('imticketId', $imTicketObj->get('pha_ewh_imticket_id'));
                $this->assign('loginUser', $loginUser);
                $this->assign('selectedProvider', $imTicketObj->get('pha_provider_id'));
                $this->assign('defaultVat', $imTicketObj->get('vat'));
                $this->assign('datePart', $datePart);
                $this->assign('selectedPhaItemType', $imTicketObj->get('enum_item_type'));
                $this->assign('note', $imTicketObj->get('note'));
                $this->assign('arrItemOfImTicket', $arrItemsOfImTicket);
            } else {
                $this->assign('imticketCode', '');
                $this->assign('imticketId', '');
                $this->assign('loginUser', '');
                $this->assign('selectedProvider', '');
                $this->assign('defaultVat', '');
                $this->assign('datePart', $datePart);
                $this->assign('selectedPhaItemType', '');
                $this->assign('note', '');
                $this->assign('arrItemOfImTicket', null);
            }
            $result['result'] = $this->view->render('edit_imticket_page.html');

        } catch (EwhImportException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionEditImTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionEditImTicketAjax fail. Error detail: '. $ex->getMessage());

        }


        $this->logger->info('Finish actionEditImTicketAjax');
        return json_encode($result);
    }




    public function actionCreateImTicketAjax() {
        $this->logger->info('Start actionCreateImTicketAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        $this->assignDefaultValueforCreatingImTicket();
        $data = array(
        'input_user_id'     =>  $this->_me->get_person_id(),
        'date'              =>  $_POST['date'],
        'enum_item_type'    =>  $_POST['enumItemType'],
        'pha_provider_id'   =>  $_POST['providerId'],        
        'vat'               =>  $_POST['vat'],
        'note'              =>  $_POST['note']
        );
        //$datePart =  L10nHelper::getDateParts(L10nHelper::renderDateTime($date,'short', 'datetime'));
        try
        {
            $result['result'] = $this->phaImportPro->createImportTicket($data);

        } catch (EwhImportException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionCreateImTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionCreateImTicketAjax fail. Error detail: '. $ex->getMessage());

        }       
        $this->logger->info('Finish actionCreateImTicketAjax');
        return json_encode($result);
    }


    /**
     * Only save meta data of import ticket
     * @return unknown_type
     */

    public function actionSaveImTicketAjax() {
        $this->logger->info('Start actionSaveImTicketAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        $imTicketId = $_POST["imTicketId"];
        $data = array(
        'input_user_id'     =>  $this->_me->get_person_id(),
        'date'              =>  $_POST['date'],
        'enum_item_type'    =>  $_POST['enumItemType'],
        'pha_provider_id'   =>  $_POST['providerId'],        
        'vat'               =>  $_POST['vat'],
        'note'              =>  $_POST['note']
        );
        try {
            $result['result'] = $this->phaImportPro->saveImTicket($imTicketId, $data);

        } catch (EwhImportException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionSaveImTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionSaveImTicketAjax fail. Error detail: '. $ex->getMessage());

        }


        $this->logger->info('Finish actionSaveImTicketAjax');
        return json_encode($result);
    }
    /**
     * add imported drug material into database
     * @return id of created record
     */
    public function actionAddDrugMaterialAjax() {
        $this->logger->info('Start actionAddDrugMaterialAjax');
        $drugMaterialId = $_POST['drugMaterialId'];
        $enumItemType = $_POST['enumItemType'];        
        $drugMaterialInputName = $_POST['drugMaterialInputedName'];
        $data = array(
            'pha_ewh_imticket_id' => $_POST['imTicketId'],
            'pha_drug_material_id' => $_POST['drugMaterialId'],
            'im_lot' => $_POST['lot'],
            'im_quantity' => $_POST['quantity'],
            'im_expired_date' => $_POST['expiredDate'],
            'im_unit_price' => $_POST['unitPrice'],
            'remain_quantity' => $_POST['quantity']
        );

        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        try {
            $this->phaImportPro->validateInputtedDrugMaterial($drugMaterialId, $drugMaterialInputName, $enumItemType);
            $result['result'] = $this->phaImportPro->addDrugMaterial($data);

        } catch (EwhImportException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionSaveImTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionSaveImTicketAjax fail. Error detail: '. $ex->getMessage());

        }

        $this->logger->info('Finish actionAddDrugMaterialAjax');
        return json_encode($result);
    }
    
/**
     * add imported drug material into database
     * @return id of created record
     */
    public function actionValidateDrugMaterialAjax() {
        $imTicketId = $_POST['imTicketId'];
        $drugMaterialId = $_POST['drugMaterialId'];
        $enumItemType = $_POST['enumItemType'];        
        $drugMaterialInputName = $_POST['drugMaterialInputedName'];
        
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        try {
            
            $this->phaImportPro->validateInputtedDrugMaterial($drugMaterialId, $drugMaterialInputName, $enumItemType);
            $this->phaImportPro->checkDuplicatedDrugMaterial($imTicketId, $drugMaterialId);
                    
        } catch (EwhImportException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionSaveImTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionSaveImTicketAjax fail. Error detail: '. $ex->getMessage());
        }
        
        $this->logger->info('Finish actionAddDrugMaterialAjax');
        return json_encode($result);
    }
    /**
     * add imported drug material into database
     * @return id of created record
     */
    public function actionDeleteDrugMaterialAjax() {
        $this->logger->info('Start actionAddDrugMaterialAjax');
        $imticketId = $_POST['imTicketId'];
        $imticketDetailId = $_POST['addedDrugMaterialId'];
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        $result['result'] = $this->phaImportPro->deleteDrugMaterial($imticketId, $imticketDetailId);
        $this->logger->info('Finish actionAddDrugMaterialAjax');
        return json_encode($result);
    }

    private function assignDefaultValueforCreatingImTicket() {

        $loginUser = array(
    	    'userId'=> $this->_me->get_person_id(),
    	    'userName'=> $this->_me->get_person_name()
        );
        $providers = Celini::newOrdo('PhaProvider')->listProviders(true);
        $orders =   L10nHelper::getYMDorder();

        $phaItemTypes = Utils::getEnumArrayKey(EnumerationConstant::PHA_ITEM_TYPE);
        $selectedPhaItemType = EnumerationConstant::PHA_ITEM_TYPE_DRUG_KEY;
        $vatList = array(
            '0'=>'0', 
            '1'=>'1',
            '2'=>'2',
            '3'=>'3',
            '4'=>'4',
            '5'=>'5',
            '6'=>'6',
            '7'=>'7',
            '8'=>'8',
            '9'=>'9',
            '10'=>'10'
            );
            $defaultVat = 5;
            $this->assign('imticketCode', '');
            $this->assign('imticketId', '');
            $this->assign('loginUser', $loginUser);
            $this->assign('providers', $providers);
            $this->assign('selectedProvider', '');
            $this->assign('datePart_0', $orders[0]);
            $this->assign('datePart_1', $orders[1]);
            $this->assign('datePart_2', $orders[2]);
            $this->assign('vatList', $vatList);
            $this->assign('defaultVat', $defaultVat);
            $this->assign('datePart', '');
            $this->assign('phaItemTypes', $phaItemTypes);
            $this->assign('selectedPhaItemType', $selectedPhaItemType);
            $this->assign('note','');
             
    }

    private function assignDefaultValueforEditingImTicket() {

        $providers = Celini::newOrdo('PhaProvider')->listProviders(true);
        $orders =   L10nHelper::getYMDorder();

        $phaItemTypes = Utils::getEnumArrayKey(EnumerationConstant::PHA_ITEM_TYPE);
        $selectedPhaItemType = EnumerationConstant::PHA_ITEM_TYPE_DRUG_KEY;
        $vatList = array(
            '0'=>'0', 
            '1'=>'1',
            '2'=>'2',
            '3'=>'3',
            '4'=>'4',
            '5'=>'5',
            '6'=>'6',
            '7'=>'7',
            '8'=>'8',
            '9'=>'9',
            '10'=>'10'
            );
            $this->assign('providers', $providers);
            $this->assign('datePart_0', $orders[0]);
            $this->assign('datePart_1', $orders[1]);
            $this->assign('datePart_2', $orders[2]);
            $this->assign('vatList', $vatList);
            $this->assign('phaItemTypes', $phaItemTypes);
            $this->assign('note','');
             
    }

     

}
?>